let dataSize = 1000
let dataName = "userList"
let dataCache = null

/**
 * 自动生成随机list
 * @param {*} length 数字，长度
 * @param {*} listName  字符串，例如："userList"
 * @param {*} props 数组，例如：["name", "age"]
 */
function randomList(options){
    const defaultOps = {
        length: dataSize,
        listName: dataName,
        props: [
            {
              prop: "name", 
              type:"string"
            }, {
              prop:"age",
              type: "number"
            }
        ]
    }

    options = options ? Object.assign({}, defaultOps, options) : defaultOps

    let i = 0
    const arr = []
    const hasId =  options.props.find(prop => prop === "id")
    dataSize = options.length
    dataName = options.listName

    if(typeof options.length !== "number"){
        throw Error("length 必须是 number 类型！")
    }

    if(typeof options.listName !== "string"){
        throw Error("listName 必须是 string 类型！")

    }

    if(Object.prototype.toString.call(options.props) !== "[object Array]"){
        throw Error("props 属性必须是数组类型，且数组元素是 string 类型！")
    }

    function add0 (num = 0){
        let str0 = ""
        let j = 0
        while(j < num){
            str0+="0"
            j++
        }

        return str0
    }

    function getRandomNum (num = 100) {
        const strLen = num.toString().length
        const randomNum = parseInt(Math.random()*num).toString()

        if(randomNum.length < strLen){
            let str0 = add0(strLen - randomNum.length)

            return str0 + randomNum
        }

        return randomNum
    }


    while(i<options.length){
        let item = Object.create(null)

        if(!hasId){
            item.id = i + 1
        }

        if(options.props && Object.prototype.toString.call(options.props) === "[object Array]"){
            options.props.forEach(node => {
                if(node.type == "string"){
                    const num = getRandomNum(options.length)
                    item[node.prop] = node.prop + num
                }

                if(node.type == "number"){
                    const num = getRandomNum(100)
                    item[node.prop] = num
                }
  
            })

            arr.push(item)
        }

        i++
    }

    const data = Object.create(null)
    data[options.listName] = arr
    dataCache = data
    // console.log("data:", data)
    return data
}


// 模拟实现的分页数据
export function getPageData (pageNum = 1, pageSize = 20) {
    if(dataCache[dataName]){
        let start = pageSize * (pageNum - 1)
        let end = start + pageSize

        if(start > dataSize-1){
            return [] 
        }

        if(end >= dataSize - 1){
            end = dataSize - 1
        }

        return {
            [dataName]: dataCache[dataName].slice(start, end),
            pageNum,
            pageSize,
            totalSize: dataSize
        }
    }
}

// 模拟实现的随机数据list
export default randomList
